<template>
  <view class="barcode-container">
    <!-- 使用 uni-barcode 原生组件 -->
    <uni-barcode
      v-if="code"
      :ref="barcodeRef"
      :code="code"
      :width="width"
      :height="height"
      @success="onSuccess"
      @fail="onFail"
    ></uni-barcode>
    <view v-else class="empty-barcode">暂无条形码数据</view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, nextTick } from 'vue';

const props = defineProps({
  // 条形码内容
  code: {
    type: String,
    default: ''
  },
  // 条形码宽度，单位为 rpx（适应不同屏幕尺寸）
  width: {
    type: [Number, String],
    default: 600
  },
  // 条形码高度，单位为 rpx（适应不同屏幕尺寸）
  height: {
    type: [Number, String],
    default: 120
  },
  // 条形码类型，可选 'code128'、'ean13' 等
  type: {
    type: String,
    default: 'code128'
  },
  // 是否自动生成条形码
  autoGenerate: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['success', 'fail']);
const barcodeRef = ref(null);
const isBarcodeGenerated = ref(false);

// 条形码生成成功回调
const onSuccess = (event) => {
  console.log('条形码生成成功:', event);
  isBarcodeGenerated.value = true;
  emit('success', event);
};

// 条形码生成失败回调
const onFail = (event) => {
  console.error('条形码生成失败:', event);
  isBarcodeGenerated.value = false;
  emit('fail', event);
};

// 初始化条形码
const initBarcode = async () => {
  if (!props.code || !barcodeRef.value || !props.autoGenerate) return;
  
  try {
    // 等待DOM更新完成
    await nextTick();
    
    // 设置条形码类型和内容
    barcodeRef.value.setType({
      type: props.type
    });
    
    barcodeRef.value.refresh({
      code: props.code
    });
    
    console.log('条形码初始化成功');
  } catch (error) {
    console.error('条形码初始化失败:', error);
    onFail({ errMsg: '条形码初始化失败', error });
  }
};

// 监听 code 变化，更新条形码
watch(() => props.code, (newCode) => {
  if (newCode && barcodeRef.value) {
    barcodeRef.value.refresh({
      code: newCode
    });
    console.log('条形码内容更新:', newCode);
  }
});

// 监听 type 变化，更新条形码类型
watch(() => props.type, (newType) => {
  if (newType && barcodeRef.value) {
    barcodeRef.value.setType({
      type: newType
    });
    console.log('条形码类型更新:', newType);
  }
});

// 组件挂载后初始化条形码
onMounted(() => {
  initBarcode();
});
</script>

<style scoped>
.barcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 10rpx 0;
}

.empty-barcode {
  width: 100%;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 28rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}
</style>    